package com.uphone.kingmall.activity.personal.set;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.china.zhuoyue.BuildConfig;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.base.UserCertifyBean;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.utils.CaptureFileUtils;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.HttpParamsUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.PermissionsUtils;
import com.uphone.kingmall.view.SubmitButton;
import com.wildma.idcardcamera.camera.CameraActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * <pre>
 *     author : 王雨
 *     e-mail : sunzengyan@outlook.com
 *     time   : 2018/07/31
 *     desc   :实名认证
 *     version: 1.0
 * </pre>
 */
public class RealNameAuthenteActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.et_id)
    EditText etId;
    @BindView(R.id.iv_id_card1)
    ImageView ivIdCard1;
    @BindView(R.id.iv_id_card2)
    ImageView ivIdCard2;
    @BindView(R.id.btn_quren)
    SubmitButton btnQuren;
    private int type = 0;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_real_name_authente;
    }

    @Override
    public void initView() {
        setStatusBar();
        btnQuren.setRelaViews(etId, etRealName);
    }

    @Override
    public void initData() {

        OkGoUtils.normalRequest(MyUrl.getUserCertify, null, new onNormalRequestListener() {
            @Override
            public void onSuccess(String body, int code) {
                if (code == 0) {
                    UserCertifyBean bean = GsonUtils.getGson().fromJson(body, UserCertifyBean.class);
                    if (bean != null && bean.getCertify() != null) {
                        RealNameAuthenteActivity.this.bean = bean;
                        UserCertifyBean.CertifyBean certify = bean.getCertify();
                        etRealName.setText(certify.getTrueName() + "");
                        etId.setText(certify.getIdno() + "");
                        Glide.with(RealNameAuthenteActivity.this).load(certify.getIdFrontImg()).into(ivIdCard1);
                        Glide.with(RealNameAuthenteActivity.this).load(certify.getIdBackImg()).into(ivIdCard2);
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    @OnClick({R.id.iv_back, R.id.iv_id_card1, R.id.iv_id_card2, R.id.btn_quren})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_id_card1:
                type = 0;
//                showDialog();
                //正面

                CameraActivity.toCameraActivity(this, CameraActivity.TYPE_IDCARD_FRONT);
                break;
            case R.id.iv_id_card2:
                type = 1;
//                showDialog();
                // 反面
                CameraActivity.toCameraActivity(this, CameraActivity.TYPE_IDCARD_BACK);
                break;
            case R.id.btn_quren:
                if (CommonUtil.checkViewEmpty(new String[]{"请输入姓名", "请输入身份证号"}, etRealName, etId)) {
                    return;
                }
                if (card1File == null) {
                    ToastUtils.showShort("请上传身份证正面照片");
                    return;
                }
                if (card2File == null) {
                    ToastUtils.showShort("请上传身份证反面照片");
                    return;
                }
                HttpParams params = HttpParamsUtils.getInstance()
                        .put("trueName", etRealName.getText().toString().trim())
                        .put("idno", etId.getText().toString().trim())
                        .put("idFrontImg", card1File, card1File.getName())
                        .put("idBackImg", card2File, card2File.getName())
                        .getParams();
                LogUtils.e("card1File :" + card1File.getName() + "     " + card2File.getName());
                if (bean != null && bean.getCertify() != null && !TextUtils.isEmpty(bean.getCertify().getId())) {
                    params.put("cerId", bean.getCertify().getId());
                }
                CommonUtil.submitNetAndFinish(this, MyUrl.subCertity, params, "提交成功！");
                break;
        }
    }


    private static final int PHOTO_REQUEST_CAMERA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static final String PHOTO_FILE_NAME1 = "temp_photo1.jpg";
    private static final String PHOTO_FILE_NAME2 = "temp_photo2.jpg";
    private File tempFile;
    private File cropPhoto;
    private File card1File;
    private File card2File;
    private static final int PHOTO_REQUEST_CUT = 3;
    private UserCertifyBean bean;

    private void showDialog() {
        final CharSequence[] items = {"相册", "拍照"};
        AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int item) {
                        // 这里item是根据选择的方式，
                        PermissionsUtils.getInstance().checkPermissions(RealNameAuthenteActivity.this, new PermissionsUtils.IPermissionsResult() {
                            @Override
                            public void passPermissions() {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    if (item == 0) {
                                        Intent intent = new Intent(Intent.ACTION_PICK);
                                        intent.setType("image/*");
                                        startActivityForResult(intent,
                                                PHOTO_REQUEST_GALLERY);
                                    } else {
                                        StartTakePhoto();

                                    }
                                } else {
                                    if (item == 0) {
                                        Intent intent = new Intent(Intent.ACTION_PICK);
                                        intent.setType("image/*");
                                        startActivityForResult(intent,
                                                PHOTO_REQUEST_GALLERY);
                                    } else {
                                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                            tempFile = new File(Environment
                                                    .getExternalStorageDirectory(),
                                                    PHOTO_FILE_NAME);
                                            Uri uri = Uri.fromFile(tempFile);
                                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                            startActivityForResult(intent,
                                                    PHOTO_REQUEST_CAMERA);
                                        } else {
                                            ToastUtils.showShort("未找到存储卡，无法存储照片！");
                                        }
                                    }

                                }
                            }

                            @Override
                            public void refusePermissions() {

                            }
                        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                }).create();
        dlg.show();
    }

    void StartTakePhoto() {
        tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        CaptureFileUtils.startActionCapture(this, tempFile, PHOTO_REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CameraActivity.REQUEST_CODE && resultCode == CameraActivity.RESULT_CODE) {
            //获取图片路径，显示图片
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
//                    final String path = ;
//                    LogUtils.e("path:" + path + "type:" + type);
                    if (!TextUtils.isEmpty(CameraActivity.getImagePath(data))) {
                        if (type == 0) {
                            card1File = new File(CameraActivity.getImagePath(data));
                            ivIdCard1.setImageBitmap(BitmapFactory.decodeFile(card1File.getAbsolutePath()));
                            if (card2File !=null){
                                ivIdCard2.setImageBitmap(BitmapFactory.decodeFile(card2File.getAbsolutePath()));
                            }
                        } else {
                            card2File = new File(CameraActivity.getImagePath(data));
                            ivIdCard2.setImageBitmap(BitmapFactory.decodeFile(card2File.getAbsolutePath()));
                            if (card1File !=null){
                                ivIdCard1.setImageBitmap(BitmapFactory.decodeFile(card1File.getAbsolutePath()));
                            }
                        }
                    }
                }
            }, 200);
        }
//                imageView.setImageBitmap(BitmapFactory.decodeFile(path));
    }
 /*else if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    crop(uri, 1);
                }
            } else {
                Log.e("radish", "图片NOT ");
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                if (tempFile != null && tempFile.exists()) {
                    LogUtils.e("tempFile.getPath()：" + tempFile.getPath());
                    crop(Uri.fromFile(tempFile), 0);
                }
            } else {
                Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                final byte[] bytes = InputStream2ByteArray(cropPhoto.getAbsolutePath());
                if (bytes != null && bytes.length > 0) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (type == 0) {
                                card1File = new File(cropPhoto.getAbsolutePath());
                                Glide.with(RealNameAuthenteActivity.this).load(bytes).into(ivIdCard1);
                            } else {
                                card2File = new File(cropPhoto.getAbsolutePath());
                                Glide.with(RealNameAuthenteActivity.this).load(bytes).into(ivIdCard2);
                            }
                            try {
                                if (tempFile != null && tempFile.exists()) {
                                    tempFile.delete();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 200);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/


    private byte[] InputStream2ByteArray(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


    private void crop(Uri uri, int type) {
        Uri outputUri;

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }

        if (type == 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".myFileProvider", tempFile);
            } else {
                uri = Uri.fromFile(tempFile);
            }
        }
        if (this.type == 0) {
            cropPhoto = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME1);
        } else {
            cropPhoto = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME2);
        }
        if (cropPhoto.exists()) {
            cropPhoto.delete();
        }
        try {
            cropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputUri = Uri.fromFile(cropPhoto);


        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        }
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        //输出的宽高
        intent.putExtra("outputX", 278);
        intent.putExtra("outputY", 155);

        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }
}
